<?php

namespace App\Http\Controllers;

use App\HuatiOwner;
use App\User;
use Illuminate\Http\Request;
use App\Wechat;

/**
 * Class WechatController
 * @package App\Http\Controllers
 */
class WechatController extends Controller
{


    /**
     * 获取code
     * @param $key
     * @return \Illuminate\Http\JsonResponse
     */
    public function getcode($key)
    {
        $appid = env('WECHAT_APPID');
        $redirect_uri = urlencode("https://wechat.jkbanlv.com/getopenid/$key");
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
        return redirect($url);
    }

    /**
     * 分享的页面获取code
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function getcodeShare(Request $request)
    {
        $path = $request->path;
        if (strpos($path, 'shop') !== false) {
            $url = Wechat::WRITER_URL;
        } else if (strpos($path, 'writer') !== false) {
            $url = 'https://fair.jkbanlv.com/login';
        } else {
            $url = Wechat::REDIRECT_URL . $path . '?token=';
        }
        $url = urlencode($url);
        $appid = env('WECHAT_APPID');
        $redirect_uri = urlencode("https://wechat.jkbanlv.com/share/getopenid?url=$url");
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
        return redirect($url);
    }


    /**
     * 获取openid
     * @param Request $request
     * @param $key
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function getopenid(Request $request, $key)
    {
        if ($request->has('code')) {
            $code = $request->code;
            $userinfo = Wechat::GetUserInfo($code);
            $user = User::UserCheck($userinfo, "/getcode/$key");

            if ($user['status'] === 1) {
                if (!array_key_exists($key, Wechat::$url)) {
                    $key = 'home';
                }
                //如果是圈子  校验是否是圈主
                if ($key === "community" && !HuatiOwner::IsOwner($user['c_id'])) {
                    return redirect('https://wechat.jkbanlv.com/community/error');
                }
                //如果是写手
                if ($key === "writer") {
                    $openid = $userinfo['openid'];
                    $url = Wechat::WRITER_URL . $openid;

                    //如果是商城
                } else if ($key === "shop") {
                    $url = Wechat::SHOP_URL . $user['c_id'];
                } else {
                    $token = $user['return'];
                    $url = Wechat::$url[$key] . "$token";
//                    return redirect($url);
                }
                return redirect($url);

            }
        }
        return redirect("/getcode/$key");
    }


    /**
     * 分享页面获取openid
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function getopenidShare(Request $request)
    {
        if ($request->has('code')) {
            $code = $request->code;
            $url = $request->url;
            $userinfo = Wechat::GetUserInfo($code);
            if ($url === Wechat::WRITER_URL) {
                return redirect($url . $userinfo['openid']);
            }
            $user = User::UserCheck($userinfo, $url);

            if ($user['status'] === 1) {
                $token = $user['return'];

                $url = $url . $token;

                return redirect($url);
            }
        }
        return redirect("/getcode/luntan");
    }


    /**
     * 用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GeoIp2\Exception\AddressNotFoundException
     * @throws \MaxMind\Db\Reader\InvalidDatabaseException
     */
    public function userinfo(Request $request)
    {
        $hash_id = $request->token;
        $userinfo = User::UserInfo($hash_id);
        return response()->json(['result' => $userinfo]);
    }


    /**
     * 获得签名
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSign(Request $request)
    {
        $path = $request->path;
        //是否有汉字
        $tagsDtl = strpos($path, 'tagsDtl');
        $result = strpos($path, 'result');
        $topicSpace = strpos($path, 'topicSpace');
        $replay = strpos($path, 'replay ');
        $findResult = strpos($path, 'findResult ');
        if ($tagsDtl !== false || $result !== false || $topicSpace !== false || $replay !== false || $findResult !== false) {
            //如果没有参数
            if ($end = strrpos($path, '?')) {
                $str_before = substr($path, 0, strrpos($path, '/')) . '/';
                $str_after = str_after($path, '?');
                $start = strrpos($path, '/');
                $millde = urlencode(substr($path, $start + 1, $end - $start - 1));
                $path = $str_before . $millde . '?' . $str_after;
            } else {
                $str_before = substr($path, 0, strrpos($path, '/')) . '/';
                $path = $str_before . urlencode(str_after(strrchr($path, '/'), '/'));

            }

        }

        return response()->json(Wechat::GetSign($path));
    }

}